<?php

namespace App\Models;

use App\Clients\CrmClient;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Media extends Model
{
    use HasFactory;
    use HasDateTimeFormatter;

    const CACHE_MEDIA_KEY = "__cache_media_key__";

    protected $casts =[
        'rules' => 'json'
    ];

    protected static $rules = null;


    public static function getRules()
    {
        if (!static::$rules)
            static::$rules = static::query()->get();

        return static::$rules;
    }

    public static function checkMedia($clue)
    {
        $rules = static::getRules();
        foreach ($rules as $rule) {
            if (DispatchRule::validateClueOfRule($clue, $rule->rules, $rule->rule_type))
                return $rule;
        }
        return null;
    }

    public static function refreshMediaType() {
        $data = CrmClient::make()->getMediaTypeList();
        if ($data) {
            Cache::put(self::CACHE_MEDIA_KEY, $data);
        }
        return $data;
    }

    public static function getMediaType()
    {
        $data = Cache::get(self::CACHE_MEDIA_KEY);
        if (!$data) {
            return self::refreshMediaType();
        }
        return $data;

    }
}
